from time import sleep
import telebot

from llm_response.llm_response import ask_llm_common, ask_llm5, \
    ask_llm7, ask_llm11, ask_llm13, ask_llm16, ask_llm17, \
    ask_llm19, ask_llm21, ask_llm22, ask_llm23, ask_llm25, ask_llm27, \
    ask_llm28, ask_llm30, ask_llm32, \
    ask_llm_minute, ask_llm1_1, ask_llm1_2, ask_llm1_3, ask_llm2_4, ask_llm2_3, ask_llm2_2, ask_llm2_1, \
    ask_llm2_5, ask_llm2_6, ask_llm1_4, ask_llm_img, ask_llm4_0, ask_llm20_1

from sql_con.select_utr_status import get_utr_status
from uitls.parse.parse_order import parse_order_ids
from uitls.reqquests_post import get_channel_type, get_payment_inquiry_pdf, get_order_submitted_backend, \
    get_exchange_rate_balance_distribution, get_cash_success_rate, \
    get_cash_in_interval_success_rate, get_cash_in_day_success_rate, get_cash_out_speed
import redis
import json
TOKEN = '7702930752:AAGYV0-kGJgMTavSPKxqdgo8tkR_gdthYJI'
bot = telebot.TeleBot(TOKEN)

# 连接本地 Redis（默认端口 6379）
r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='yb@123456')
# r = redis.Redis(host='127.0.0.1', port=6379, db=0, password=None)

def re_exr(llm_resp, text, data, message):
    # 1代收通道是否正常
    if llm_resp == '1':
        llm_minute = ask_llm_minute(text)
        cash_in_interval_json = json.loads(get_cash_in_interval_success_rate(data, llm_minute))
        cash_in_day_json = json.loads(get_cash_in_day_success_rate(data))
        result = {
            'cash_in_interval_json': str(cash_in_interval_json),
            'cash_in_day_json': str(cash_in_day_json)
        }
        ask_llm2_6(str(result))

        if cash_in_day_json['status'] == 200 and cash_in_interval_json['status'] == 200:
            if cash_in_interval_json['data']['lastCashInSucNum'] == 0:
                succ_rate = 0
            else:
                succ_rate = (cash_in_interval_json['data']['lastCashInSucNum']) / (
                    cash_in_interval_json['data']['lastCashInTotalNum'])

            if cash_in_day_json['data']['lastCashInSucNum'] == 0:
                day_succ_rate = 0
            else:
                day_succ_rate = (cash_in_day_json['data']['lastCashInSucNum']) / (
                    cash_in_day_json['data']['lastCashInTotalNum'])

            diff = abs(succ_rate - day_succ_rate)

            if succ_rate < 0.1:
                return ask_llm1_1()
            else:
                if diff < 0.1:
                    return ask_llm1_2()
                else:
                    return ask_llm1_3()
        else:
            return ask_llm1_4()

    # 2代付通道是否正常，代付速度怎么样
    if llm_resp == '2':
        llm_minute = ask_llm_minute(text)
        speed = get_cash_out_speed(data, llm_minute)
        print("speed", speed)
        cash_out = json.loads(speed)

        print("cash_out", cash_out)
        if cash_out['status'] == 200:
            if cash_out['data']['lastCashOutSucNumWithin1Min'] <= 1:
                return ask_llm2_1()
            if 1 < cash_out['data']['lastCashOutSucNumWithin10Min'] <= 10:
                return ask_llm2_2()
            if 10 < cash_out['data']['lastCashOutSucNumWithin30Min'] <= 30:
                return ask_llm2_3()
            if cash_out['data']['lastCashOutSucNumWithin30Min'] > 30:
                return ask_llm2_4()
        else:
            return ask_llm2_5()


    # 5UTR已被使用
    if llm_resp == '5':
        utr_response = ask_llm7(text)
        text_response = get_utr_status(utr_response)
        if text_response is not None:
            llm_response = ask_llm5(text_response)
            return llm_response
        else:
            return '没有查询到UTR账号'

    # 6代付订单失败原因
    if llm_resp == '6':
        order_ids = ask_llm20_1(text)
        order_data_ids = parse_order_ids(order_ids)
        print("order_id:", order_data_ids)
        if order_data_ids == "无" or order_data_ids == "":
            return "没有查到订单号噢"
        else:
            urgent_order = get_payment_inquiry_pdf(data, order_data_ids['order_ids'][0])
            try:
                data_order = json.loads(urgent_order)
                if data_order['status'] == 200:
                    l = len(data_order['data']['orderInfo']['payoutSourceOrders'])
                    upstream_order = data_order['data']['orderInfo']['payoutSourceOrders'][l - 1]['order_ref']
                    bot.send_message(-4805059187, f'''{upstream_order}\n麻烦查询下这笔代付订单具体失败原因是？''')
                    data1 = {
                        "chat_id": message.chat.id,
                        "message_id": message.message_id,
                    }
                    r.set(upstream_order, json.dumps(data1), ex=2592000)
                    return "稍等老板 帮您核查中"
                else:
                    return "该订单不存在，请查询接口信息。"
            except json.JSONDecodeError:
                print("不是 JSON，原始输出：", urgent_order)
                data_order = {"status": "201"}  # 兜底，直接包一层
                return

    # 7支持的通道类型
    if llm_resp == '7':
        data = get_channel_type(data)
        # print(data)
        if data is not None:
            llm_response = ask_llm11(data)
            return llm_response
        else:
            return '没有查询到支持的通道类型'

    # 8代收成功率怎么样
    # if llm_resp == '8':
    #     print("8代收成功率怎么样")
    #     data = get_cash_success_rate(data)
    #     print(data)
    #     if data is not None:
    #         llm_response = ask_llm32(data)
    #         return llm_response
    #     else:
    #         return "代收成功率为空"

    # 10查询余额
    if llm_resp == '10':
        data = get_exchange_rate_balance_distribution(data)
        if data is not None:
            llm_response = ask_llm27(data)
            return llm_response
        else:
            return '查询余额为空'

    # 11查询下发汇率
    if llm_resp == '11':
        data = get_exchange_rate_balance_distribution(data)
        if data is not None:
            llm_response = ask_llm28(data)
            return llm_response
        else:
            return "查询下发汇率空"

    # 12订单xxx是否提交到我们后台
    if llm_resp == '12':
        order = ask_llm25(text)
        data = get_order_submitted_backend(order, data)
        if data is not None:
            text_response = "您好，该订单已经成功提交到我们后台"
            llm_response = ask_llm_common(text_response)
            return llm_response
        else:
            text_response = "您好，该订单暂未提交到我们后台，请贵司技术查询"
            llm_response = ask_llm_common(text_response)
            return llm_response

    # 13如何使用公钥，密钥
    if llm_resp == '13':
        if ask_llm13(text) == 'y':
            text_response = "公钥我们私发给你"
            llm_response = ask_llm_common(text_response)
            return llm_response
        else:
            text_response = "密钥可以在商户后台拿到"
            llm_response = ask_llm_common(text_response)
            return llm_response

    # 14测试环境和正式环境的回调ip是否一致
    if llm_resp == '14':
        text_response = "测试环境和正式环境的回调ip不一致"
        llm_response = ask_llm_common(text_response)
        return llm_response

    # 15测试环境，正式环境回调
    if llm_resp == '15':
        if ask_llm16(text) == 'y':
            text_response = "测试环境自动回调"
            llm_response = ask_llm17(text_response)
            return llm_response
        else:
            text_response = "正式环境的回调需要询问运维人员"
            llm_response = ask_llm17(text_response)
            return llm_response

    # 16资金流水备注的文字意思
    if llm_resp == '16':
        llm_response = ask_llm19(text)
        return llm_response


def re_exr_file(save_path, payoutOrder):
    # 9代付查单让商户提供流水pdf

    # print("text",text)
    # order_id = ask_llm20_1(text)
    # print("order_id:", order_id)
    # print("address", address)
    # data = get_payment_inquiry_pdf(address, order_id)

    print("data", payoutOrder)
    sleep(21)

    res_data_str = ask_llm21(payoutOrder)
    sleep(21)

    res_pdf_str = ask_llm22(res_data_str, save_path)
    sleep(21)

    print("res_pdf_str", res_pdf_str)
    print("res_data_str", res_data_str)
    # 拼接为新JSON对象
    result = {
        'res_pdf': res_pdf_str,
        'res_data': res_data_str
    }
    llm_response = ask_llm23(str(result))
    return llm_response


def re_exr_img(save_path, order):
    if order != "":
        llm_response = ask_llm_img(order, save_path)
        return llm_response
    else:
        return "上游没有utr"


def re_exr_operation_people():
    text = ask_llm30()
    return text
def payout_wallet_account_mobile_number(message):
    bot.reply_to(message, "用的都是手机电子钱包，手机号就是账号，所以要一致才能出款。")
    print("用的都是手机电子钱包，手机号就是账号，所以要一致才能出款。")

def internal_deposit_u_address(message):
    bot.reply_to(message, "商户内充及更换提U地址仅可在每日 10:00 - 19:00 期间进行")
    print("商户内充及更换提U地址仅可在每日 10:00 - 19:00 期间进行")


def new_merchant_login_dashboard(message):
    bot.reply_to(message, "第一次密码输入正确 ，会弹出二维码的。麻烦重新复制密码粘贴进去看下会展示不～")
    print("第一次密码输入正确 ，会弹出二维码的。麻烦重新复制密码粘贴进去看下会展示不～")

def simulated_payout(message):
    bot.reply_to(message, "钱包代付的话account 是个手机号08后面8-11位数字比如 08123456789")
    print("钱包代付的话account 是个手机号08后面8-11位数字比如 08123456789")

def merchant_key_reset(message):
    bot.reply_to(message, "第一次登录后台拿秘钥的时候需要 不然看不到全部显示，只有重置后更换新的并展示全部")
    print("第一次登录后台拿秘钥的时候需要 不然看不到全部显示，只有重置后更换新的并展示全部")

def test_environment_collection_callback(message):
    bot.reply_to(message, "测试环境 代收下发的链接需要打开。填写钱包帐号 03123456789。提交之后 一分钟后就会自动回调成功")
    print("测试环境 代收下发的链接需要打开。填写钱包帐号 03123456789。提交之后 一分钟后就会自动回调成功")


def indonesian_commands(message):
    bot.reply_to(message, '''代收查单格式：/piq +订单号+付款凭证\n代付查单格式：/poq+订单号\n查询余额：/bal@DeepayServiceBot\n获取支付凭证：/proof+订单号
        ''')
    print("印尼指令")

def indian_commands(message):
    bot.reply_to(message, '''
        代收订单格式：\n1.（凭证图片+订单号+bd）\n2./payin +订单号+utr\n（两种方式都可以自助查单）\n3.代付凭证指令：/payout+订单号\n4.代付状态指令：/poq+订单号
        ''')
    print("印度指令")
def bangladesh_commands(message):
    bot.reply_to(message, '''代收查单格式：\n1.（凭证图片+订单号+bd）\n2./payin +订单号+流水号（两种方式都可以自助查单）\n3.代付查单格式：/poq+订单号\n4.查询余额：/bal@DeepayServiceBot\n5.获取支付凭证：/proof+订单号
        ''')
    print("孟加拉指令")

def pakistan_commands(message):
    bot.reply_to(message, '''代收查单格式：\n1.（凭证图片+订单号+bd）\n2./payin +订单号+流水号（两种方式都可以自助查单）\n3.代付查单格式：/poq+订单号\n4.查询余额：/bal@DeepayServiceBot\n5.获取支付凭证：/proof+订单号
            ''')
    print("巴基斯坦指令")
